define(window.backboneCommon.getViewDefine("targets.index"), function ($,require,Collection,tpl,ViewTime,ViewArea,ViewAudience,ViewInterest,ViewDevice,ViewKeyWord,ViewAppAction,ViewCrowd) {
    var defaultsOptions={
        modalElement:"#container_target_modal",
        selectData:{},
        isOperate:true,
        checkAreaCallback:null,
        checkCrowdCallback:null
    };
    var pagePrivate = {
        getDefaults :function () {
            return defaultsOptions
        },
        getOptions : function (options) {
            options=$.ExtCommon.isCheckEmpty(options)?{}:options;
            return $.ExtCommon.initMergeJson(this.getDefaults(),options);
        }
    };
    var backboneView= Backbone.View.extend({
        events: {
            "click #panel_target .target-edit": "editTarget",
            "click #panel_target .target-delete": "deleteTarget"
        },
        initialize: function () {
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(options){
            this.elementModel={
               table:$("#tb_listTarget")
            };
            this.extObject={};
            this.pageData={initPage:false};
            this.pageOptions=$.ExtCommon.initMergeJson(pagePrivate.getOptions(),options);
            var trTargets=[
                {type:"time",title:"时间"},{type:"area",title:"地域"},{type:"audience",title:"人口属性"},{type:"interest",title:"商业兴趣"},
                {type:"device",title:"移动设备"},{type:"appAction",title:"APP行为"},{type:"keyword",title:"关键字"},{type:"crowd",title:"自定义人群"}
            ];
            $("#panel_targetAdd").html($("#template_target_btnAdd").render(trTargets));
            this.elementModel.table.children("tbody").html($("#template_target_info").render(trTargets));
            $(this.pageOptions.modalElement).html($("#template_target_container").render(trTargets));
            this.initViewAttach();
            this._initBind();
        },
        initPage:function (options) {
            this.pageOptions=$.ExtCommon.initMergeJson(this.pageOptions,options);
            this.pageOptions.selectData=options.selectData||{};
            this._initBind()
        },
        _initBind:function () {
            this.elementModel.table.find("thead>tr").children().eq(2).toggle(this.pageOptions.isOperate);
            $("#panel_targetAdd").toggle(this.pageOptions.isOperate).children(".btn").prop("disabled", !this.pageOptions.isOperate);
            this.bindInfo(this.pageOptions.selectData);
        },
        initViewAttach:function () {
            var self=this;
            self.viewAttach={};
            self.viewAttach.time=new ViewTime({pElement:"#container_target_modal_time", submitCallback:function(json){self.time(json)}});
            self.viewAttach.area=new ViewArea({pElement:"#container_target_modal_area", submitCallback:function(json){self.area(json)}});
            self.viewAttach.audience=new ViewAudience({pElement:"#container_target_modal_audience", submitCallback:function(json){self.audience(json)}});
            self.viewAttach.interest=new ViewInterest({pElement:"#container_target_modal_interest", submitCallback:function(json){self.interest(json)}});
            self.viewAttach.device=new ViewDevice({pElement:"#container_target_modal_device", submitCallback:function(json){self.device(json)}});
            self.viewAttach.keyword=new ViewKeyWord({pElement:"#container_target_modal_keyword", submitCallback:function(json){self.keyword(json)}});
            self.viewAttach.appAction=new ViewAppAction({pElement:"#container_target_modal_appAction", submitCallback:function(json){self.appAction(json)}});
            self.viewAttach.crowd=new ViewCrowd({pElement:"#container_target_modal_crowd", submitCallback:function(json){self.crowd(json)}});
        },
        editTarget:function (e) {
            if(this.pageOptions.isOperate){
                var type=$(e.currentTarget).data("targetOperate");
                var data=this.elementModel.table.data(type);
                switch(type) {
                    case "time":
                        this.viewAttach.time.init(data?data.selectedValue:{});
                        break;
                    case "area":
                        var areaDataType;
                        if(this.pageOptions.checkAreaCallback){
                            areaDataType=this.pageOptions.checkAreaCallback();
                        }
                        this.viewAttach.area.init(data,areaDataType);
                        break;
                    case "keyword":
                        this.viewAttach.keyword.init(data?data.value:"");
                        break;
                    case "crowd":
                        $.ExtNotify.destroy();
                        if(this.pageOptions.checkCrowdCallback){
                            var customer=this.pageOptions.checkCrowdCallback();
                            if(!$.ExtCommon.isCheckEmpty(customer)){
                                this.viewAttach.crowd.init(data,{customerId:customer.toString()==="-1"?"":customer})
                            }
                        }
                        break;
                    default:
                        this.viewAttach[type].init(data);
                        break;
                }
            }
        },
        deleteTarget:function (e) {
            if(this.pageOptions.isOperate) {
                var type = $(e.currentTarget).data("targetOperate");
                this[type]({});
            }
        },
        getSelectData: function () {
            var targetParam = {};
            var tbTargetData = this.elementModel.table.data();
            if (tbTargetData.time) {
                targetParam.time = tbTargetData.time.arrValue;
            }
            if (tbTargetData.area) {
                var jsonArea = {};
                for (var i = 0; i < tbTargetData.area.length; i++) {
                    var arrTempArea = tbTargetData.area[i].id.split("_");
                    jsonArea[arrTempArea[0]] = arrTempArea[1]
                }
                targetParam.area = jsonArea;
            }
            if (tbTargetData.audience) {
                if (tbTargetData.audience.gender)targetParam.gender = $.ExtCommon.convertArrByPara(tbTargetData.audience.gender);
                if (tbTargetData.audience.education)targetParam.education = $.ExtCommon.convertArrByPara(tbTargetData.audience.education);
                if (tbTargetData.audience.marriage)targetParam.marriage = $.ExtCommon.convertArrByPara(tbTargetData.audience.marriage);
                if(tbTargetData.audience.age)targetParam.age=tbTargetData.audience.age;
            }
            if (tbTargetData.interest) {
                targetParam.interest = $.ExtCommon.convertArrByPara(tbTargetData.interest);
            }
            if (tbTargetData.device) {
                if (tbTargetData.device.connection)targetParam.connection = $.ExtCommon.convertArrByPara(tbTargetData.device.connection);
                if (tbTargetData.device.os)targetParam.os = $.ExtCommon.convertArrByPara(tbTargetData.device.os);
                if (tbTargetData.device.telCom)targetParam.telCom = $.ExtCommon.convertArrByPara(tbTargetData.device.telCom);
            }
            if (tbTargetData.keyword) {
                targetParam.keyword = tbTargetData.keyword.value;
            }
            if(tbTargetData.appAction){
                targetParam.appAction={};
                if(tbTargetData.appAction.category){targetParam.appAction.category=$.ExtCommon.convertArrByPara(tbTargetData.appAction.category);}
                if(tbTargetData.appAction.action){targetParam.appAction.action=$.ExtCommon.convertArrByPara(tbTargetData.appAction.action);}
                if(tbTargetData.appAction.fromDay){targetParam.appAction.fromDay=parseInt(tbTargetData.appAction.fromDay);}
            }
            if (tbTargetData.crowd) {
                targetParam.crowd = $.ExtCommon.convertArrByPara(tbTargetData.crowd);
            }
            return targetParam;
        },
        bindInfo: function (json) {
            this.time($.ExtCommon.convertWeekHourValue(json.time));
            this.area(json.area);

            var deviceJson = {};
            if (json.os) {deviceJson.os = json.os}
            if (json.connection) {deviceJson.connection = json.connection}
            if (json.telCom) {deviceJson.telCom = json.telCom}
            this.device(deviceJson);

            var audienceJson = {};
            if (json.gender) {audienceJson.gender = json.gender}
            if(json.age){audienceJson.age=json.age}
            if (json.education) {audienceJson.education = json.education}
            if (json.marriage) {audienceJson.marriage = json.marriage}
            this.audience(audienceJson);

            this.interest(json.interest);
            this.keyword({value: json.keyword, list:json.keyword?json.keyword.split(","):[]});
            this.crowd(json.crowd);
            this.appAction(json.appAction);

            this.showTable();
        },
        deleteData:function (type) {
            this.elementModel.table.removeData(type)
        },
        addData:function (type,json) {
            this.elementModel.table.data(type, json)
        },
        time: function (json) {
            var strHtml = "";
            if ($.ExtCommon.isCheckEmpty(json)) {
                this.deleteData("time");
            } else {
                this.addData("time", json);
                if (json.selectedHtml.length > 0) {
                    strHtml = $.map(json.selectedHtml, function (info) {
                        return info;
                    }).join("");
                }
            }
            this.bindTdHtml("#td_time", strHtml);
        },
        area: function (json) {
            var strHtml = "";
            if ($.ExtCommon.isCheckEmpty(json)) {
                this.deleteData("area");
            } else {
                this.addData("area", json);
                strHtml = '<div class="child-inline-block">'+ $.ExtCommon.getValueBySpan(json)+'</div>';
            }
            this.bindTdHtml("#td_area", strHtml);
        },
        audience: function (json) {
            var strHtml = "";
            if ($.ExtCommon.isCheckEmpty(json)) {
                this.deleteData("audience");
            } else {
                this.addData("audience", json);
                var arrHtml = [];
                if (!$.ExtCommon.isCheckEmpty(json.gender)) {arrHtml.push($.ExtCommon.getValueByParagraph("性别", "45", json.gender))}
                if (!$.ExtCommon.isCheckEmpty(json.education)) {arrHtml.push($.ExtCommon.getValueByParagraph("学历", "45", json.education))}
                if (!$.ExtCommon.isCheckEmpty(json.marriage)) {arrHtml.push($.ExtCommon.getValueByParagraph("婚恋", "45", json.marriage))}
                if (!$.ExtCommon.isCheckEmpty(json.age)) {arrHtml.push($.ExtCommon.getValueByParagraph("年龄", "45", json.age+"岁"))}
                strHtml = arrHtml.join("")
            }
            this.bindTdHtml("#td_audience", strHtml);
        },
        interest: function (json) {
            var strHtml = "";
            if ($.ExtCommon.isCheckEmpty(json)) {
                this.deleteData("interest");
            } else {
                this.addData("interest", json);
                strHtml = '<div class="child-inline-block">'+ $.ExtCommon.getValueBySpan(json)+'</div>';
            }
            this.bindTdHtml("#td_interest", strHtml);
        },
        device: function (json) {
            var strHtml = "";
            if ($.ExtCommon.isCheckEmpty(json)) {
                this.deleteData("device");
            } else {
                this.addData("device", json);
                var arrHtml = [];
                if (!$.ExtCommon.isCheckEmpty(json.os)) {arrHtml.push($.ExtCommon.getValueByParagraph("操作系统", "75", json.os))}
                if (!$.ExtCommon.isCheckEmpty(json.connection)) {arrHtml.push($.ExtCommon.getValueByParagraph("联网方式", "75", json.connection))}
                if (!$.ExtCommon.isCheckEmpty(json.telCom)) {arrHtml.push($.ExtCommon.getValueByParagraph("运营商", "60", json.telCom))}
                strHtml = arrHtml.join("");
            }
            this.bindTdHtml("#td_device", strHtml);
        },
        keyword: function (json) {
            var strHtml = "";
            if ($.ExtCommon.isCheckEmpty(json.list)) {
                this.deleteData("keyword");
            } else {
                this.addData("keyword", json);
                strHtml = '<div class="child-inline-block">'+ $.ExtCommon.getValueBySpan(json.list)+'</div>';
            }
            this.bindTdHtml("#td_keyword", strHtml);
        },
        appAction:function(json){
            var strHtml="";
            if($.ExtCommon.isCheckEmpty(json)){
                this.deleteData("appAction");
            }else {
                this.addData("appAction", json);
                var arrHtml = [];
                if (!$.ExtCommon.isCheckEmpty(json.category)) {arrHtml.push($.ExtCommon.getValueByParagraph("分类", "55", json.category));}
                if (!$.ExtCommon.isCheckEmpty(json.action)) {arrHtml.push($.ExtCommon.getValueByParagraph("行为", "55", json.action));}
                if (!$.ExtCommon.isCheckEmpty(json.fromDay)) {arrHtml.push($.ExtCommon.getValueByParagraph("距今日", "55", json.fromDay+"天以内"));}
                strHtml=arrHtml.join("");
            }
            this.bindTdHtml("#td_appAction",strHtml);
        },
        crowd:function (json) {
            var strHtml = "";
            if ($.ExtCommon.isCheckEmpty(json)) {
                this.deleteData("crowd");
            } else {
                this.addData("crowd", json);
                strHtml = '<div class="child-inline-block">'+ $.ExtCommon.getValueBySpan(json)+'</div>';
            }
            this.bindTdHtml("#td_crowd", strHtml);
        },
        bindTdHtml: function (id, strHtml) {
            var tr=$(id).parents("tr:first");
            if (strHtml.length > 0) {
                $(id).html(strHtml);
                tr.addClass("tr-show").show();
            } else {
                $(id).html("");
                tr.removeClass("tr-show").hide();
            }
            tr.children().eq(2).toggle(this.pageOptions.isOperate);
            this.showTable();
        },
        showTable: function () {
            if (this.elementModel.table.find(".tr-show").length > 0) {
                this.elementModel.table.parent().show();
            } else {
                this.elementModel.table.parent().hide();
            }
        }
    });
    var viewModel=function(options){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el:options.pElement,collection:this.collection,model:this.model});
        this.view.initMain(options);
    };
    viewModel.prototype={
        init:function (options) {
            this.view.initPage(options);
        },
        getValue:function () {
           return this.view.getSelectData();
        },
        deleteArea:function () {
            this.view.area({})
        },
        deleteCrowd:function () {
            this.view.crowd({})
        }
    };
    return viewModel;
});